package pe.edu.sistemas.samupg.business.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import pe.edu.sistemas.samupg.domain.model.Noticia;
import pe.edu.sistemas.samupg.domain.model.Noticia_;

/**
 * 
 * @author Marlon
 */
@Stateless
public class NoticiaBean extends AbstractBean<Noticia> {

	@PersistenceContext(unitName = "samupgPU")
	private EntityManager em;

	@Override
	protected EntityManager getEntityManager() {
		return em;
	}
	
	@SuppressWarnings("unchecked")
	public List<Noticia> findNoticiasxRange(Integer maximum) {

		if (maximum == 0) {
			String sql = "SELECT p from Noticia n order by n.fechaCreacion DESC";
			return em.createQuery(sql).getResultList();
		}

		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Noticia> cq = cb.createQuery(Noticia.class);
		Root<Noticia> n = cq.from(Noticia.class);
		cq.select(n);
		cq.orderBy(cb.desc(n.get(Noticia_.fechaCreacion)));
		Query q = em.createQuery(cq);
		q.setMaxResults(maximum);
		q.setFirstResult(0);
		return q.getResultList();
	}

	public NoticiaBean() {
		super(Noticia.class);
	}
}
